package top.codedance.iotp.server.net;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.ServerMeta;
import top.codedance.iotp.common.util.DeviceIdUtil;
import top.codedance.iotp.common.util.HttpRequestUtil;
import top.codedance.iotp.common.util.MacUtils;
import top.codedance.iotp.server.ServerApplication;
import top.codedance.iotp.server.net.session.Session;
import org.apache.log4j.Logger;

import java.util.List;

public class RegistryExecutor {
    private static Logger logger = ServerApplication.getLogger(RegistryExecutor.class);

    private String ip = "0.0.0.0";
    private int tcpPort;
    private int httpPort;
    private int wsPort;

    public RegistryExecutor(String ip, int tcpPort, int httpPort, int wsPort) {
        this.ip = ip;
        this.tcpPort = tcpPort;
        this.httpPort = httpPort;
        this.wsPort = wsPort;
    }

    public void run() {
        while (true) {
            registy();
            try {
                Thread.sleep(1000*5);
                logger.debug("Registing update server !");
            } catch (Exception ex) {
            }
        }

    }

    public void registy(){
        try {
            final ServerMeta sm = new ServerMeta();
            if(ip.equals("0.0.0.0")){
                List<String> hostIps = MacUtils.getHostIp();
                if(hostIps.size() > 0){
                    sm.setBindIp(hostIps.get(0));
                }
            }else{
                sm.setBindIp(ip);
            }
            sm.setBindIp(sm.getBindIp());
            sm.setHttpBindHost(ServerApplication.httpBindHost);
            sm.setWsBindHost(ServerApplication.wsBindHost);
            sm.setTcpPort(this.tcpPort);
            sm.setHttpPort(httpPort);
            sm.setWsPort(wsPort);
            sm.setNetUsername(ServerApplication.netUsername);
            sm.setNetPassword(ServerApplication.netPassword);
            sm.setWeight(ServerApplication.weight);
            final JSONObject jsonObject = new JSONObject();
            jsonObject.put("serverMeta", sm.toString());

            ServerApplication.loadBlanceRegists((registryHost) -> {
                JSONObject post = HttpRequestUtil.post(registryHost + "/rest/api/server/register", jsonObject.toJSONString());
                if (post.getIntValue("status") != 200) {
                    return null;
                }else{
                    return "success";
                }
            });

            for (String deviceId : TcpServer.sessionManager.getClientDeviceIds()) {
                if (DeviceIdUtil.checkIsClient(deviceId)) {
                    ServerApplication.loadBlanceRegists((registryHost) -> {
                        Session session = TcpServer.sessionManager.getSessionByDeviceId(deviceId);
                        JSONObject registryJSONObject = new JSONObject();
                        registryJSONObject.put("deviceId", session.getDeviceId());
                        registryJSONObject.put("server", sm.getBindIp() + ":" + ServerApplication.tcpPort);
                        JSONObject post = HttpRequestUtil.post(registryHost + "/rest/api/client/register", registryJSONObject.toJSONString());
                        if (post.getIntValue("status") != 200) {
                            return null;
                        }else{
                            return "success";
                        }
                    });
                }
            }
        } catch (Exception ex) {
            logger.debug(ex.getMessage());
        }
    }
}
